
/**** overide ****/
function toPage(element,props,url){
    props=props||{};
    if(!url){
      url="/manage/main.html#/"+element+"?"+$.param(props);
    }
    history.pushState({element:element,props:props},"",url);
    mountElement(element,props)
    //API.wxConfig();
}

/*****  manager ******/

var TopNavBar = React.createClass({
    render: function(){
        return (
<nav className="navbar navbar-inverse navbar-static-top">
    
        <div className="navbar-header">
            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                <span class="sr-only">菜单</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a className="navbar-brand" href="#">商户管理平台</a>
        </div>
        <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul className="nav navbar-nav mm">
                <li><a href="#">进入店铺</a></li>
            </ul>
            <ul className="nav navbar-nav navbar-right">
                <li><a href="/login.html"><sapn className="userinfo">退出</sapn></a></li>
                <li className="dropdown">
                </li>
            </ul>
        </div>
</nav>)
    }
});

var SideNavBar = React.createClass({
    render: function(){
        var partnerBtns=[];
        var staffBtns=[];
        var customerBtns=[];
        var flag=$.cookie("flag")||"";
        if(flag.indexOf("p")>=0){
              partnerBtns.push(<li><a onClick={function(){toPage('StatisticPage',{partnerId:this.props.partnerId})}.bind(this)}  href="javascript:;">店铺数据</a></li>);
              partnerBtns.push(<li><a onClick={function(){toPage('ShopMngPage',{partnerId:this.props.partnerId})}.bind(this)}  href="javascript:;">店铺管理</a></li>);
              partnerBtns.push(<li><a onClick={function(){toPage('OrderMngPage',{partnerId:this.props.partnerId})}.bind(this)}  href="javascript:;">订单管理</a></li>);
              partnerBtns.push(<li><a onClick={function(){toPage('ProductMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">商品管理</a></li>);
              partnerBtns.push(<li><a onClick={function(){toPage('PromotionMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">优惠活动</a></li>);
          }
        if(flag.indexOf("a")>=0){
              staffBtns.push(<li><a href="javascript:;">顾客管理</a></li>);
              staffBtns.push(<li><a onClick={function(){toPage('FlowMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">账户流水</a></li>);
              staffBtns.push(<li><a onClick={function(){toPage('InvoiceMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">应付账款</a></li>);
              staffBtns.push(<li><a onClick={function(){toPage('AdvertisementMngPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">广告管理</a></li>);
              staffBtns.push(<li><a href="javascript:;">自定义页面</a></li>);
              staffBtns.push(<li><a href="javascript:;">导航管理</a></li>);
              staffBtns.push(<li><a href="javascript:;">主题风格</a></li>);
              staffBtns.push(<li><a href="javascript:;">相关设置</a></li>);
          }
        return (
          <div id="sidebar-wrapper">
                   <ul className="sidebar-nav">
                        {customerBtns}
                        {partnerBtns}
                        {staffBtns}
                   </ul>
                   
               </div>
      )
    }
});

var SubMenuBar = React.createClass({
    render: function(){
      var msg=null;
      if(this.props.message){
        msg=<div className="alert alert-warning" role="alert">{this.props.message}</div>
      }
      var back=null;
      if(this.props.withback){
        back=<li><a className="btn btn-error" href="javascript:history.back()">返回</a></li>
      }
        return (
          <nav className="navbar navbar-default">
                <div className="navbar-header">
                    <a className="navbar-brand" href="javascript:;">{this.props.brand}</a>
                    <ul className="nav mm">
                        {back}
                        {this.props.children}
                    </ul>
                </div>
                {msg}
                <div>
                    
                </div>
        </nav>)
    }
});

var GridHeader = React.createClass({
    render: function(){
        var collection=this.props.collection||{};
        var first=collection.first||false;
        var last=collection.last||false;

        return (
        <nav className="navbar navbar-default">
              <ul className="pager pull-left btn-group">
                <button onClick={this.props.handlePrevPage} disabled={first?"disabled":false} href="javascript:;" className="btn btn-primary btn-lg"><span className="glyphicon glyphicon-menu-left"/>上页</button>
                <button onClick={this.props.handleNextPage} disabled={last?"disabled":false}  href="javascript:;" className="btn btn-primary btn-lg"><span className="glyphicon glyphicon-menu-right"/>下页</button>
                <button onClick={this.props.handleRefresh} href="javascript:;" className="btn btn-primary btn-lg"><span className="glyphicon glyphicon-refresh"/>刷新</button>
              </ul>
              <div className="pull-left"></div>
              <div>
                <ul className="nav  mm">
                    <li><a href="#">{this.props.children}</a></li>
                </ul>
              </div>
              <ul className="pull-right">
                  共{collection.totalElements||0}条记录
              </ul>
        </nav>)
    }
});

var GridPageMixin = {
    loadData:function(){

    },
    pagerAction:function(action){
        if(action>0&&!this.state.collection.last){
          this.state.page++;
          this.loadData();
        }else if(action<0&&!this.state.collection.first){
          this.state.page--;
          this.loadData();
        }
        
    },
    getInitialState: function() {
            return {content:[],collection:{},page:0,totalPages:0};
    },
    componentDidMount: function(){
        this.loadData();
    }
};

var ShopGrid = React.createClass({
    handleShopInactive:function(shop){
      if(confirm("是否要取消本次预定?")){
        $.post('/api/partners/'+this.props.partnerId+'/shops/'+shop.id+'/inactive',function(){
          if(this.props.onUpdated)
            this.props.onUpdated()
        }.bind(this))
      }
    },
   render: function(){
       var items=this.props.shops.map(function(shop){
        var time=new Date(shop.createTime).Format("yyMMddhh");
            return (<tr><td>{shop.name}</td><td>{shop.address}</td><td>{time}</td><td>{shop.contact}</td><td><button className="btn btn-primary" onClick={function(){toPage('ShopPage',{partnerId:this.props.partnerId,shop:shop})}.bind(this)}><span className="glyphicon glyphicon-edit"/></button> <button onClick={this.handleShopInactive.bind(this,shop)} className="btn btn-error"><span className="glyphicon glyphicon-trash"/></button></td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>名称</th><th>金额</th><th>时间</th><th></th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }
})

var ProductGrid = React.createClass({
    handleProductActive:function(product){
      $.post('/api/partners/'+this.props.partnerId+'/products/'+product.id+'/active',function(){
        if(this.props.onUpdated)
          this.props.onUpdated()
      }.bind(this))
    },
    handleProductInactive:function(product){
      if(confirm("确定要删除?")){
        $.post('/api/partners/'+this.props.partnerId+'/products/'+product.id+'/inactive',function(){
          if(this.props.onUpdated)
            this.props.onUpdated()
        }.bind(this))
      }
    },
    render: function(){
        var self=this;
        var partnerId=this.props.partnerId;
        var items = this.props.products.map(function(product){
            var opBtn=product.active?<button className="btn btn-warning" onClick={this.handleProductInactive.bind(this,product)}><span className="glyphicon glyphicon-remove"/></button>:<button onClick={this.handleProductActive.bind(this,product)} className="btn btn-success"><span className="glyphicon glyphicon-ok"/></button>
            return (<tr><td>{product.name}</td><td>{product.price}</td><td>{product.stock}</td><td>{product.cat1}</td><td>{product.shopName}</td><td>{product.brand}</td><td>{opBtn}<button onClick={function(){toPage('ProductPostPage',{partnerId:partnerId,product:product},'#/product/edit?'+product.id)}.bind(this)} className="btn btn-primary"><span className="glyphicon glyphicon-edit"/></button></td></tr>)
        }.bind(this))
        return (<div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>名称</th><th>价格</th><th>库存</th><th>分类</th><th>店铺</th><th>品牌</th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>);
    }
});





var FlowGrid = React.createClass({
   render: function(){
       var items=this.props.billflows.map(function(billflow){
        var time=new Date(billflow.createTime).Format("yyMMddhh");
            return (<tr><td className="hidden-xs">{billflow.shortId}</td><td>{billflow.name}</td><td>{billflow.amount}</td><td>{time}</td><td>{billflow.balance}</td><td className="hidden-xs">{billflow.note}</td><td className="hidden-xs">{billflow.orderId}</td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th className="hidden-xs">流水号</th><th>名称</th><th>金额</th><th>时间</th><th>余额</th><th className="hidden-xs">备注</th><th className="hidden-xs">关联订单号</th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }
})


var OrderGrid = React.createClass({
    render:function(){
      var items=this.props.orders.map(function(order){
          var time=new Date(order.createTime).Format("yyMMddhh");
            return (<tr><td>{order.id}</td><td>{time}</td><td>{order.receiver}</td><td>{order.receiverPhone}</td><td>{order.statusText}</td><td>{order.total}</td><td>{order.payment}</td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>订单编号</th><th>下单时间</th><th>顾客</th><th>联系电话</th><th>状态</th><th>订单总额</th><th>支付方式</th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
    }
})

var InvoiceGrid = React.createClass({
   render: function(){
       var items=this.props.invoices.map(function(invoice){
            var time=new Date(invoice.createTime).Format("yyMMddhh");
            return (<tr><td>{invoice.name}</td><td>{invoice.amount}</td><td>{time}</td><td>{invoice.statusText}</td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>名称</th><th>金额</th><th>时间</th><th>状态</th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }
})

var PartnerApplicationGrid = React.createClass({
   handleApplicationApprove:function(appId){
        $.post('/api/admin/applications/'+appId+'/approve',{approved:true},function(data){
          if(this.props.onUpdated)
            this.props.onUpdated()
        }.bind(this));
   },
   handleApplicationReject:function(appId){
        $.post('/api/admin/applications/'+appId+'/reject',{rejected:true},function(data){
          if(this.props.onUpdated)
            this.props.onUpdated()
        }.bind(this));
   },
   render: function(){
       var items=this.props.apps.map(function(app){
            var time=new Date(app.createTime).Format("yyMMddhh");
            return (<tr><td>{app.submiter.username}</td><td>{app.name}</td><td>{app.address}</td><td>{app.contact}</td><td>{time}</td><td><button onClick={this.handleApplicationApprove.bind(this,app.id)} className="btn btn-success">通过</button><button onClick={this.handleApplicationReject.bind(this,app.id)} className="btn btn-warning">拒绝</button></td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>提交人</th><th>名称</th><th>地址</th><th>联系人</th><th>提交时间</th><th>提交时间</th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }
})


var PartnerGrid = React.createClass({

  render: function(){
       var items=this.props.partners.map(function(partner){
            var time=new Date(partner.createTime).Format("yyMMddhh");
            return (<tr className={partner.active?"active":"inactive"}><td>{partner.name}</td><td>{partner.amount}</td><td>{time}</td><td><button onClick={toPage.bind(this,'PartnerPostPage',{partner:partner},'#/PartnerPostPage')} className="btn btn-success"><span className="glyphicon glyphicon-edit"/></button><button onClick={toPage.bind(this,'FlowMngPage',{partnerId:partner.id},'#/FlowMngPage')} className="btn btn-success"><span className="glyphicon glyphicon-btc"/></button></td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>名称</th><th></th><th>时间</th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }

});


var PartnerFollowGrid = React.createClass({
  handleChange:function(c,e){
    console.log(c,e.target.value)
    $.post('/api/partners/'+partnerId+'/follow/'+c+'/metadata',{customId:e.target.value},function(){
      //alert('done')
      
    })
  },
  render: function(){
       var items=this.props.follows.map(function(follow){
            var time=new Date(follow.createTime).Format("yyMMddhh");
            var attributes=follow.metaData.attributes||{};
            return (<tr><td><img width="64" src={"/api/thumb/"+follow.target.picture+"/64/64"}/></td><td>{follow.target.name}</td><td>{time}</td><td><ContentEditable onChange={this.handleChange.bind(this,follow.target.id)}>{attributes.customId}</ContentEditable></td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th></th><th>名称</th><th>时间</th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }

});

var PromotionRulesGrid = React.createClass({
  handleDeletePromotion:function(rule){
    API.deletePromotionRulesOfPartner({partnerId:this.props.partnerId,id:rule.id},function(){
      if(this.props.onUpdated)
        this.props.onUpdated()
    }.bind(this))
  },
  render:function(){
    var items=this.props.rules.map(function(rule){
            var time=new Date(rule.createTime).Format("yyMMddhh");
            return (<tr><td>{rule.name}</td><td>{rule.amount}</td><td>{rule.type}</td><td>{rule.active}</td><td>
              <button onClick={this.handleDeletePromotion.bind(this,rule)} className="btn btn-warning"><span className="glyphicon glyphicon-trash" /></button>
              <button onClick={function(){toPage('PromotionRulePostPage',{partnerId:this.props.partnerId,rule:rule},'#/promotions?id='+rule.id)}.bind(this)} className="btn btn-primary"><span className="glyphicon glyphicon-edit" /></button>
              </td></tr>);
       }.bind(this))
    return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th>名称</th><th>金额</th><th>类型</th><th></th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
  }
})

var AdvertisementGrid = React.createClass({
  handleDeleteAdvertisement:function(advertisementId){
    $.post('/api/admin/advertisements/'+advertisementId,{active:false},function(data){
      if(this.props.onUpdated)
        this.props.onUpdated()
    }.bind(this))
  },
  render: function(){
       var items=this.props.advertisements.map(function(advertisement){
          var product = advertisement.product||{}
          var picture = '/api/thumb/'+advertisement.picture+'/64/64'
          return (<tr><td><img src={picture} /></td><td>{advertisement.name}</td><td>{advertisement.level}</td><td>{advertisement.prority}</td><td><button onClick={this.handleDeleteAdvertisement.bind(this,advertisement.id)} className="btn btn-warning"><span className="glyphicon glyphicon-trash" /></button></td></tr>);
       }.bind(this))
       return (<div>
            <div className="panel panel-success">
                  <div className="panel-body table-responsive">
                  <table className="table table-striped table-condensed">
                  <tr><th></th><th>名称</th><th></th><th></th></tr>
                  {items}
                  </table>
                  </div>
              </div>
            </div>);
   }
})

var ShopList4Partner = React.createClass({
    handleOpenModal: function(){
        $('#shopModal').modal('show');
    },
    render: function() {
        var shopOptions=this.props.shops.map(function(shop){
            return (<option value={shop.id} >{shop.name}</option>);
        });

        return (
            <div className="input-group">
               <span className="input-group-addon">场地：</span>
               <select name="shop_id" className="form-control" value={this.props.selected}>
                {shopOptions}
               </select>
               <span className="input-group-btn"><a onClick={this.handleOpenModal} className="btn btn-default" type="button"> 新增场地 </a></span>
            </div>
         );
    }
});

var LineChartSummary = React.createClass({
  getInitialState: function() {
    return {
      start:this.props.start||new Date(new Date().getTime()-7*24*3600000),end:this.props.end||new Date()
      ,data:[]
    };
  },
  forward:function(){
    this.state.start=new Date(this.state.start.getTime()-7*24*3600000);
    this.setState({start:this.state.start});
    this.loadData();
  },
  backward:function(){
    this.state.end=new Date(this.state.end.getTime()+7*24*3600000);
    this.setState({end:this.state.end});
    this.loadData();
  },
  loadData:function(){
    $.get('/api/partners/'+this.props.partnerId+'/reports/summary',{start:this.state.start.Format('yyyyMMdd'),end:this.state.end.Format('yyyyMMdd')},function(data){
      this.setState({data:data})
    }.bind(this))
  },
  componentDidMount: function(){
      var ctx = $('canvas',this.getDOMNode()).get(0).getContext("2d");
      this.chart = new Chart(ctx);
      this.loadData();
  },
  render:function(){
    if(this.chart){
      var labels=this.state.data.map(function(item){
        return item.key;
      })
      var data_pv=this.state.data.map(function(item){
        return item.visited;
      })
      var data = {
          labels: labels,
          datasets: [
              {
                  label: "浏览量 (PV)",
                  fillColor: "rgba(220,220,220,0.2)",
                  strokeColor: "rgba(220,220,220,1)",
                  pointColor: "rgba(220,220,220,1)",
                  pointStrokeColor: "#fff",
                  pointHighlightFill: "#fff",
                  pointHighlightStroke: "rgba(220,220,220,1)",
                  data: data_pv
              }
          ]
      };
      this.chart.Line(data);
    }
    return(
      <div className="panel panel-info">
        <div className="panel-heading bg-info">
          <div className="text-center">{this.state.start.Format('yyyy-MM-dd')} ~ {this.state.end.Format('yyyy-MM-dd')} </div>
          <div className="btn-group">
            <button onClick={this.forward}  href="javascript:;" className="btn btn-primary btn-lg"><span className="glyphicon glyphicon-menu-left"/>更多</button>
            <button onClick={this.backward} disabled={true}  href="javascript:;" className="btn btn-primary btn-lg"><span className="glyphicon glyphicon-menu-right"/></button>
          </div>
        </div>
        <div className="panel-body">
          <canvas id="partnerChart" className="chart col-xs-12"></canvas>
        </div>
      </div>
      )
  }
});

/****** manage pages *********/

var StatisticPage = React.createClass({
    loadData:function(){
      $.get('/api/partners/'+this.props.partnerId+'/reports/oneday',function(data){
        this.setState({summary:data[0]})
      }.bind(this))
    },
    getInitialState: function() {
            return {summary:{"incoming":0,"visited":10,"key":"20150618","order":0,"sold":0},pv:{week:[],month:[]},sales:{week:[],month:[]}};
    },
    render:function(){
      var summary=this.state.summary||{};
        return (<div>
        <SubMenuBar brand="店铺数据"><li></li></SubMenuBar>
        <div className="row">
          <div className="col-xs-12 col-md-3 text-center ">
            <div className="panel panel-info">
              <div className="bg-info panel-heading">今日数据</div>
              <div className="panel-body">
                <div>浏览量(PV)</div>
                <div>{summary.visited}</div>
                <div>成交单数(笔)</div>
                <div>{summary.order}</div>
                <div>销售额</div>
                <div>{summary.incoming}</div>
                <div>销售量</div>
                <div>{summary.sold}</div>
                
              </div>
            </div>
          </div>
          <div className="col-xs-12 col-md-9">
            <LineChartSummary partnerId={this.props.partnerId} />
          </div>
        </div>
        
      </div>)
    }
});

var PartnerApplicationMngPage = React.createClass({
    loadData:function(){
      $.get('/api/admin/applications',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="合作申请"><li><button className="btn btn-primary" onClick={toPage.bind(this,'PartnerMngPage',{},null)}>现有合作商</button></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <PartnerApplicationGrid onUpdated={this.loadData} apps={this.state.content}/>
        </div>)
    }
});

$.extend(PartnerApplicationMngPage.prototype,GridPageMixin);

var PartnerMngPage = React.createClass({
    loadData:function(){
      $.get('/api/admin/partners',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="合作商管理"><li><button className="btn btn-primary" onClick={toPage.bind(this,'PartnerApplicationMngPage',{},null)}>合作申请</button></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <PartnerGrid onUpdated={this.loadData} partners={this.state.content}/>
        </div>)
    }
});

$.extend(PartnerMngPage.prototype,GridPageMixin);

var PartnerFollowMngPage = React.createClass({
    loadData:function(){
      $.get('/api/partners/'+this.props.partnerId+'/follow',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="会员管理"><li></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <PartnerFollowGrid partnerId={this.props.partnerId} onUpdated={this.loadData} follows={this.state.content}/>
        </div>)
    }
});

$.extend(PartnerFollowMngPage.prototype,GridPageMixin);


var ShopMngPage = React.createClass({
    loadData:function(){
      var flag=$.cookie("flag")||"";
      if(flag.indexOf("a")>=0){
        $.get('/api/admin/shops',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
      }else{
        $.get('/api/partners/'+this.props.partnerId+'/shops',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
      }
      
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="店铺管理"><li><a className="btn btn-success" onClick={function(){toPage('ShopPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">添加店铺</a></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <ShopGrid onUpdated={this.loadData} shops={this.state.content} partnerId={this.props.partnerId}/>
        </div>)
    }
});

$.extend(ShopMngPage.prototype,GridPageMixin);

var ProductMngPage = React.createClass({
    loadData:function(){
      $.get('/api/partners/'+this.props.partnerId+'/products',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="商品管理"><li><a className="btn btn-success" onClick={function(){toPage('ProductPostPage',{partnerId:this.props.partnerId})}.bind(this)} href="javascript:;">添加商品</a></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <ProductGrid onUpdated={this.loadData} products={this.state.content} partnerId={this.props.partnerId}/>
        </div>)
    }
});

$.extend(ProductMngPage.prototype,GridPageMixin);

var FlowMngPage = React.createClass({
    loadData:function(){
      API.flowsOfPartner({partnerId:this.props.partnerId,page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand={"资金流水"}><li></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <FlowGrid onUpdated={this.loadData} billflows={this.state.content}/>
        </div>)
    }
});

$.extend(FlowMngPage.prototype,GridPageMixin);


var PrimaryAccountMngPage = React.createClass({
    loadData:function(){
      $.get('/api/admin/accounts/main/flow',function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="主账户资金流水"><li></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <FlowGrid onUpdated={this.loadData} billflows={this.state.content}/>
        </div>)
    }
});

$.extend(PrimaryAccountMngPage.prototype,GridPageMixin);

var OrderMngPage = React.createClass({
    loadData:function(){
      API.ordersOfPartner({partnerId:this.props.partnerId,page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="订单列表"><li></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <OrderGrid onUpdated={this.loadData} orders={this.state.content}/>
        </div>)
    }
});

$.extend(OrderMngPage.prototype,GridPageMixin);


var InvoiceMngPage = React.createClass({
    loadData:function(){
      API.invoicesOutList({page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="应付账款"><li></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <InvoiceGrid onUpdated={this.loadData} invoices={this.state.content}/>
        </div>)
    }
});

$.extend(InvoiceMngPage.prototype,GridPageMixin);


var PromotionMngPage = React.createClass({
    loadData:function(){
      API.promotionRulesOfPartner({partnerId:this.props.partnerId,page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="促销策略"><li><a className="btn btn-success" onClick={function(){toPage('PromotionRulePostPage',{partnerId:this.props.partnerId},'#/promotions?id=new')}.bind(this)} href="javascript:;">添加促销策略</a></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <PromotionRulesGrid onUpdated={this.loadData} partnerId={this.props.partnerId} rules={this.state.content} refresh={this.loadData.bind(this)}/>
        </div>)
    }
});

$.extend(PromotionMngPage.prototype,GridPageMixin);

var AdvertisementMngPage = React.createClass({
    loadData:function(){
      $.get('/api/admin/advertisements',{page:this.state.page},function(data){
            this.setState({content:data.content,collection:data,page:data.number});
        }.bind(this));
    },
    render:function(){
        return (<div>
        <SubMenuBar brand="广告管理"><li><a className="btn btn-success" onClick={function(){toPage('AdvertisementPostPage',{partnerId:this.props.partnerId},'#/promotions?id=new')}.bind(this)} href="javascript:;">添加广告</a></li></SubMenuBar>
        <GridHeader collection={this.state.collection} handleRefresh={this.loadData} handlePrevPage={this.pagerAction.bind(this,-1)} handleNextPage={this.pagerAction.bind(this,1)}/>
        <AdvertisementGrid onUpdated={this.loadData} partnerId={this.props.partnerId} advertisements={this.state.content} refresh={this.loadData.bind(this)}/>
        </div>)
    }
}); 

$.extend(AdvertisementMngPage.prototype,GridPageMixin);

var FormPageMixin={
  componentDidMount: function() {
    var thisElement=this.getDOMNode();
    $('form',thisElement).validate();
    if(this.loadData)
      this.loadData();
  }
}

var ProductPostPage = React.createClass({
        getInitialState: function() {
                var customer=this.props.customer||{};
                var product=this.props.product||{};
                return {shops:[],product:{},picture:product.picture||customer.avatar};
        },
        handleSubmitProduct: function(){
            var thisElement=this.getDOMNode();
            if($('form',thisElement).valid()){
              $.post("/api/partners/"+this.props.partnerId+"/products",$('form.ProductForm',thisElement).serialize(),function(){
                  this.done?this.done():history.back();
              }.bind(this));
            }
            
        },
        loadShops:function(){
            var self=this;
            API.shopsOfPartner({partnerId:this.props.partnerId},function(data){
                self.setState({shops:data.content});
            });
        },
        loadData: function() {
            this.loadShops();
            if(this.props.productId){
              API.getProduct({productId:this.props.productId},function(data){
                this.setState({product:data,picture:data.picture})
              }.bind(this))
            }
            if(this.props.partnerId){
              API.partnerGet({partnerId:this.props.partnerId},function(data){
                this.setState({parter:data,picture:this.state.picture||data.avatar})
              }.bind(this))
            }

            
        },
        onUploaded:function(filename){
          var thisElement=this.getDOMNode();
          this.setState({picture:filename})
          console.log(filename);
          //$('#picture_id',thisElement).val(filename);
        },
        render: function() {
            var customer=this.props.customer||{};
            var product=this.props.product||{};
            var parter = this.state.parter||{};
            var picture=this.state.picture;
            return (
            <div className="clear-both">
                <SubMenuBar brand="商品管理" withback="true"><li><a onClick={this.handleSubmitProduct} href="javascript:;">保存</a></li></SubMenuBar>
                <form className="ProductForm" method="post">
                    <input type="hidden" name="_id" value={product.id||this.props.productId} />
                    <input type="hidden" name="partner_id" value={this.props.partnerId} />
                    <input type="hidden" id="picture_id" name="picture_id" value={this.state.picture} />
                    <ShopList4Partner partnerId={this.props.partnerId} shops={this.state.shops} selected={product.shopId}/>
                    <div className="input-group">
                      <span className="input-group-addon">标题：</span>
                      <input name="_name" defaultValue={product.name} type="text" className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">类型：</span>
                      <select name="cat1_name" defaultValue={product.cat1} className="form-control">
                          <option value="羽毛球">羽毛球</option>
                          <option value="篮球">篮球</option>
                          <option value="足球">足球</option>
                      </select>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">费用：</span>
                      <input name="_price" defaultValue={product.price} type="number" className="form-control" data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                      <span className="input-group-addon">.00元</span>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">不参加促销活动：</span>
                      <input name="no_promotion" defaultChecked={product.disablePromotion} type="checkbox" className="form-control"/>
                    </div>

                    <div className="input-group">
                      <span className="input-group-addon">备注：</span>
                      <input name="_remark" defaultValue={product.remark} type="text" className="form-control"/>
                    </div>
                    <div className="input-group">
                      <span className="input-group-addon">数量：</span>
                      <input name="_quantity" defaultValue={product.quantity} type="text" className="form-control" data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                    </div>
                    <FileUploader picture={picture} onUploaded={this.onUploaded}/>

                    <div className="input-group  col-xs-12 col-md-3">
                        <button onClick={this.handleSubmitProduct} type="button" className="btn btn-primary">保存</button>
                    </div>
                </form>
                <Modal id="shopModal">
                    <ShopPage partnerId={this.props.partnerId} onChange={function(){this.loadShops();}.bind(this)}/>
                </Modal>
             </div>
            );
        }
});

$.extend(ProductPostPage.prototype,FormPageMixin);

var ShopPage = React.createClass({
  handleAddShop:function(){
      $.post('/api/partners/'+this.props.partnerId+'/shops',$('form',this.getDOMNode()).serialize(),function(data){
          if(this.props.onChange){
            this.props.onChange();
          }else{
            history.back();
          }
      }.bind(this));
      $('#shopModal').modal('hide');
  },
  render:function(){
    var shop = this.props.shop||{};
    return(<div>
      <form>
          <input type="hidden" name="shop_id" value={shop.id} />
          <div className="input-group">
            <span className="input-group-addon">名称：</span>
            <input name="_name" defaultValue={shop.name} type="text" className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
            <span className="input-group-addon"></span>
          </div>

          <LocationPicker address={shop.address} location={shop.location}/>
          </form>
          <button onClick={this.handleAddShop} type="button" className="btn btn-primary col-xs-6 col-md-3">添加</button>
      </div>)
  }
})

var PredefinedRules=[
  {name:"女士优惠",property:"customerSex",amount:5,op:"equal",right:"2",stage:"1"}
  ,{name:"新人优惠",property:"joinedDays",amount:5,op:"lessThan",right:"7",stage:"1"}
]

var PromotionRulePostPage = React.createClass({
  handleSubmitRule:function(){
    var thisElement=this.getDOMNode();
    $.post("/api/partners/"+this.props.partnerId+"/promotions",$('form',thisElement).serialize(),function(){
        toPage('PromotionMngPage',{partnerId:this.props.partnerId})
    }.bind(this));
  },
  render:function(){
    var rule=this.props.rule||{};
    var quickStart='';
    if(!rule.id){
      var samples=PredefinedRules.map(function(rule){
        return <li className="list-group-item"><a onClick={toPage.bind(this,'PromotionRulePostPage',{rule:rule,partnerId:partnerId},'#//PromotionMngPage?id=new')} href="javascript:;">{rule.name}</a></li>
      })
      quickStart=(<div className="panel panel-info">
          <div className="panel-body">
            促销策略模版：
            <ul className="list-group">{samples}</ul>
          </div>
        </div>);
    }

    return (<div>
      <SubMenuBar brand="推广策略" withback="true"><li></li></SubMenuBar>
      {quickStart}
    <form>
      <input type="hidden" name="id" defaultValue={rule.id}/>
      <input type="hidden" name="type" defaultValue={rule.stage}/>
      <div className="input-group">
        <span className="input-group-addon">名称：</span>
        <input name="name" type="text" defaultValue={rule.name} className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
      </div>
      <div className="input-group">
        <span className="input-group-addon">金额：</span>
        <input name="amount" type="number" data-rule-min="0" data-msg-min="妈呀，小学没毕业不认识负数！" data-rule-required="true"  data-msg-required="此项不能为空！" defaultValue={rule.amount} className="form-control"/>
      </div>
      <div className="input-group">
        <span className="input-group-addon">条件</span>
        <select name="property" defaultValue={rule.property} className="form-control">
          <option value="joinedDays">注册天数</option>
          <option value="customerSex">性别(1=男，2=女)</option>
          <option value="total">订单金额</option>
          <option value="shippingProvince">省份</option>
        </select>

        <select name="op" defaultValue={rule.op} className="form-control"><option value="equal">等于</option><option value="greaterThan">大于</option><option value="lessThan">小于</option></select>
        <input name="right" defaultValue={rule.right} type="text" className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
      </div>
      <div className="input-group">
        <button onClick={this.handleSubmitRule.bind(this)} type="button" className="btn btn-primary">保存</button>
      </div>
    </form>
    </div>)
    
  }

})

$.extend(PromotionRulePostPage.prototype,FormPageMixin);


var AdvertisementPostPage = React.createClass({

  handleSubmitAdvertisement:function(){
    var thisElement=this.getDOMNode();
    $.post("/api/admin/advertisements",$('form',thisElement).serialize(),function(){
        toPage("AdvertisementMngPage");
    });
  },
  getInitialState: function() {
    var advertisement=this.props.advertisement||{};
    return {
      picture:advertisement.picture
    };
  },
  onUploaded:function(filename){
    this.setState({picture:filename})
    //$('#picture_id',thisElement).val(filename);
  },
  render: function() {
    var advertisement=this.props.advertisement||{};
    return (
      <div>
      <SubMenuBar brand="广告" withback="true"><li></li></SubMenuBar>
    <form>
      <input type="hidden" name="id" defaultValue={advertisement.id}/>
      <input type="hidden" id="picture_id" name="picture_id" value={this.state.picture} />
      <div className="input-group">
        <span className="input-group-addon">名称：</span>
        <input name="name" type="text" defaultValue={advertisement.name} className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
      </div>
      <div className="input-group">
        <span className="input-group-addon">链接：</span>
        <input name="url" type="text" defaultValue={advertisement.url} className="form-control" data-rule-required="true"  data-msg-required="此项不能为空！"/>
      </div>
      <div className="input-group">
        <span className="input-group-addon">级别：</span>
        <select name="level" defaultValue={advertisement.level} className="form-control">
          <option value="1">1</option>
          <option value="2">2</option>
        </select>
      </div>
        <FileUploader picture={this.state.picture} onUploaded={this.onUploaded}/>
      <div className="input-group">
        <button onClick={this.handleSubmitAdvertisement} type="button" className="btn btn-primary">保存</button>
      </div>
    </form>
    </div>
    );
  }

});

$.extend(AdvertisementPostPage.prototype,FormPageMixin);

var PartnerPostPage = React.createClass({
  loadData:function(){

  },
  handlePartnerPost:function(){
    var thisElement=this.getDOMNode()
    $.post('/api/partners/'+this.props.partner.id,$('form',thisElement).serialize(),function(data){
      alert("done")
    })
  },
  onUploaded:function(filename){
    this.setState({picture:filename})
  },
  getInitialState: function() {
    var partner=this.props.partner||{}
    return {
      picture: partner.avatar
    };
  },
  render: function() {
    var partner=this.props.partner||{}
    var contact=partner.contact||{}
    var picture=partner.avatar
    return (
          <div className="panel">
          <SubMenuBar brand="商户管理" withback="true"><li><a onClick={toPage.bind(this,'AccountPostPage',{partner:partner},'#/AccountPostPage')} href="javascript:;">修改财物资料</a></li></SubMenuBar>
           <div className="panel-body">
              <form className="PartnerApplyForm">
                <input type="hidden" name="id" value={partner.id}/>
                <input type="hidden" id="picture_id" name="picture_id" value={this.state.picture}/>
                <div className="form-group">
                  <input type="text" defaultValue={partner.name} className="form-control" name="name" id="name" placeholder="名称" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                  <label for="name" className="alert alert-default">名称</label>
                </div>
                <div className="form-group">
                  <input type="phone" defaultValue={contact.phone} className="form-control" name="contact_phone" id="phone" placeholder="电话号码" data-rule-required="true"  data-msg-required="此项不能为空！"/>
                  <label for="phone" className="alert alert-default">请输入固定号码或手机号</label>
                </div>
                <hr/>
                <FileUploader picture={picture}/>
                <hr/>
                <div className="input-group">
                  <select name="returnedRate" defaultValue={partner.returnedRate} className="form-control">
                    <option value="0">全额退款</option>
                    <option value="0.1">10%</option>
                    <option value="0.3">30%</option>
                    <option value="0.5">50%</option>
                    <option value="0.7">70%</option>
                    <option value="1">100%</option>
                  </select>
                  <label for="returnedRate" className="alert alert-default">退订收取多少比例的金额作为退订损失的弥补</label>
                </div>
                <button type="button" onClick={this.handlePartnerPost} className="btn btn-primary col-xs-12 col-md-2">提交</button>
                
              </form>
           </div>
          </div>
          )
  }
})

$.extend(PartnerPostPage.prototype,FormPageMixin);


var AccountPostPage = React.createClass({
  loadData:function(){
    $.get('/api/admin/partners/'+this.props.partner.id+'/account',function(data){
      this.setState({account:data})
    }.bind(this))
  },
  handleAccountPost:function(){
    var thisElement=this.getDOMNode()
    $.post('/api/admin/accounts/'+this.state.account.id,$('form',thisElement).serialize(),function(){
      alert('done')
    })
  },
  getInitialState: function() {
    return {
      account:{} 
    };
  },
  render: function() {
    var partner=this.props.partner||{}
    var account=this.state.account
    if(!account.payment){
      return <div>...</div>;
    }
    var payment=account.payment||{}
    return (
      <div>
        <SubMenuBar brand="商户管理" withback="true"><li><a onClick={toPage.bind(this,'AccountPostPage',{partner:partner},'#/AccountPostPage')} href="javascript:;">修改财物资料</a></li></SubMenuBar>
        <form >
          <div className="form-group">
            <input name="payment_id" defaultValue={payment.accountId} className="form-control"  type="text" placeholder="银行账号" data-rule-required="true"  data-msg-required="此项不能为空！"/>
            <label for="phone" className="alert alert-default">请输入银行账号</label>
          </div>
          <div className="form-group">
            <input name="payment_name" defaultValue={payment.accountName} className="form-control"  type="text" placeholder="账号名称" data-rule-required="true"  data-msg-required="此项不能为空！"/>
            <label for="phone" className="alert alert-default">请输入账号名称</label>
          </div>
          <div className="form-group">
            <input name="payment_institute" defaultValue={payment.institute} className="form-control"  type="text" placeholder="开户行" data-rule-required="true"  data-msg-required="此项不能为空！"/>
            <label for="phone" className="alert alert-default">请输入开户行</label>
          </div>
          <hr/>
          <div className="form-group">
            <select name="settlement_period" defaultValue={account.settlementPeriod} className="form-control">
              <option value="30">月结</option>
              <option value="7">周结</option>
              <option value="14">隔周结</option>
            </select>
            <label for="phone" className="alert alert-default">结算周期</label>
          </div>
          <button type="button" onClick={this.handleAccountPost} className="btn btn-primary col-xs-12 col-md-2">提交</button>
        </form>
      </div>
    );
  }
})

$.extend(AccountPostPage.prototype,FormPageMixin);



